﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using GMS.Utils;
using GMS.Model;
using GMS.BLL;
using GMS.Web.CommonPage;
using System.Data;
using Maticsoft.DBUtility;
using System.Drawing;
using GMS.Web.CommonPage;


//DataBindCrossTab()：将图表绑定到一个数据源，并允许基于一个数据列进行分组，
//在具体指定的列上每个唯一的值将自动创建一个单独的序列。

public partial class public_MsChart : System.Web.UI.Page
{
    DbHelper db = new DbHelper();
    TabColumns model = new TabColumns();
    TabInfo infomodel = new TabInfo();
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["tabcode"] == null)//tabcode为表名
            {
                Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='" + Request.ApplicationPath + "/Login.aspx';</script>");
                return;
            }

            chkAutoSize.Checked = true;
            txtWidth.Text = "730";
            txtHeight.Text = "500";
            SetAutoSizeCtrl();

            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                TabColumnsAccessBLL columnbll = new TabColumnsAccessBLL();
                TabInfoAccessBLL infobll = new TabInfoAccessBLL();
                string tabcode = Session["tabcode"].ToString();//tabcode为表名
                infomodel = infobll.GetModel(tabcode);//从tabinfo表获取此张表的信息
                if (model != null)
                {
                    int a = infomodel.AUTOID;
                    Session["AutoID"] = a;
                    ds = columnbll.GetX(a);//根据获取的autoid，到tabcolumn表读取此表可以作为x轴的字段
                    xcolumn.DataSource = ds;
                    xcolumn.DataTextField = "ColName";
                    xcolumn.DataValueField = "ColCode";
                    xcolumn.DataBind();
                    ds = columnbll.GetY(a);
                    ycolumn.DataSource = ds;
                    ycolumn.DataTextField = "ColName";
                    ycolumn.DataValueField = "ColCode";
                    ycolumn.DataBind();
                }
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                TabColumnsBLL columnbll = new TabColumnsBLL();
                TabInfoBLL infobll = new TabInfoBLL();
                string tabcode = Session["tabcode"].ToString();
                infomodel = infobll.GetModel(tabcode);
                if (model != null)
                {
                    int a = infomodel.AUTOID;
                    Session["AutoID"] = a;
                    ds = columnbll.GetX(a);
                    xcolumn.DataSource = ds;
                    xcolumn.DataTextField = "ColName";
                    xcolumn.DataValueField = "ColCode";
                    xcolumn.DataBind();
                    ds = columnbll.GetY(a);
                    ycolumn.DataSource = ds;
                    ycolumn.DataTextField = "ColName";
                    ycolumn.DataValueField = "ColCode";
                    ycolumn.DataBind();
                }
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                TabColumnsOraBLL columnbll = new TabColumnsOraBLL();
                TabInfoOraBLL infobll = new TabInfoOraBLL();
                string tabcode = Session["tabcode"].ToString();
                infomodel = infobll.GetModel(tabcode);
                if (model != null)
                {
                    int a = infomodel.AUTOID;
                    Session["AutoID"] = a;
                    ds = columnbll.GetX(a);
                    xcolumn.DataSource = ds;
                    xcolumn.DataTextField = "ColName";
                    xcolumn.DataValueField = "ColCode";
                    xcolumn.DataBind();
                    ds = columnbll.GetY(a);
                    ycolumn.DataSource = ds;
                    ycolumn.DataTextField = "ColName";
                    ycolumn.DataValueField = "ColCode";
                    ycolumn.DataBind();
                }
            }
            else
                return;
        }
    }

    /// <summary>
    /// 页面弹出对话框
    /// </summary>
    /// <param name="txt"></param>
    public void ToAlert(string txt)
    {
        this.Page.RegisterClientScriptBlock("", "<script>alert('" + txt + "');</script>");
    }

    private void InitChartSetting()
    {
        MsChart.Width = 730;
        MsChart.Height = 500;
        MsChart.ChartAreas["ChartArea1"].AxisX.LineWidth = 2;
        MsChart.ChartAreas["ChartArea1"].AxisY.LineWidth = 2;
        MsChart.ChartAreas["ChartArea1"].AxisX.LineColor = Color.Blue;
        MsChart.ChartAreas["ChartArea1"].AxisY.LineColor = Color.Red;
        if (DDL_Show3D.SelectedValue == "2")
            MsChart.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;//3D属性设为true
        else
            MsChart.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = false;       
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 
    private void ShowStat(DataSet ds, ListItem item, int count, bool add1)
    {
        //MsChart.DataBindCrossTable(  
       
        string name = item.ToString();
        MsChart.Series.Add(name);
        //MsChart.Series[name].YValuesPerPoint = 2;//这个可能要的
        MsChart.Series[name].IsValueShownAsLabel = true;//显示表中数值的属性
        MsChart.ChartAreas["ChartArea1"].AxisX.Title = xcolumn.SelectedItem.ToString();
        string str = "/";
        if(count == 1)
            str = "";
        MsChart.ChartAreas["ChartArea1"].AxisY.Title = MsChart.ChartAreas["ChartArea1"].AxisY.Title + str + name;
        switch (charttype.SelectedValue.ToString())//设置图表类型
        {
            case "1":
                break;
            case "2":
                MsChart.Series[name].ChartType = SeriesChartType.Line; break;

            case "3":
                MsChart.Series[name].ChartType = SeriesChartType.Pie; break;
        }

        MsChart.Series[name].XValueMember = xcolumn.SelectedValue.ToString();
        MsChart.Series[name].YValueMembers = item.Value.ToString();
        
        MsChart.Series[name].LegendText = name;
        //MsChart.Legends[0].DockedToChartArea = true;
        //MsChart.DataSource = ds;//当多个线条时，用这2句会出错的
        //MsChart.DataBind();
        DataView dv = new DataView(ds.Tables[0]);
        if(add1)
            MsChart.Series[name].Points.DataBindXY(dv, xcolumn.SelectedValue + "1", dv, item.Value);
        else
            MsChart.Series[name].Points.DataBindXY(dv, xcolumn.SelectedValue, dv, item.Value);
    }
    

    protected void xcolumn_SelectedIndexChanged(object sender, EventArgs e)
    {
       // Response.Write(xcolumn.SelectedItem.ToString());
        string selected = xcolumn.SelectedValue.ToString();
        if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
        {
            TabColumnsAccessBLL columnbll = new TabColumnsAccessBLL();
            ds = columnbll.GetType(selected);//获取所选x轴的type
        }
        else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
        {
            TabColumnsBLL columnbll = new TabColumnsBLL();
            ds = columnbll.GetType(selected);
        }
        else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
        {
            TabColumnsOraBLL columnbll = new TabColumnsOraBLL();
            ds = columnbll.GetType(selected);
        }
        int columntype=Convert.ToInt32(ds.Tables[0].Rows[0]["ColType"]);
       // Response.Write(columntype);
        if (columntype == 5)
        {   
            //ViewState["1"]
            timetype.Visible = true;
            DDL_TimeSelect.Visible = true;
            start.Visible = true;
            //starttime.Visible = true;
            end.Visible = true;
            //endtime.Visible = true;
            txtStartTime.Visible = true;
            txtEndTime.Visible = true;
            BtnComOk.Visible = false;//如果x轴是时间类型，其实呈现的button不是同一个
            BtnDateOk.Visible = true;
        }
        else
        {
            timetype.Visible = false;
            DDL_TimeSelect.Visible = false;
            start.Visible = false;
           // starttime.Visible = false;
            end.Visible = false;
           // endtime.Visible = false;
            txtStartTime.Visible = false;
            txtEndTime.Visible = false;
            BtnComOk.Visible = true;
            BtnDateOk.Visible = false;
        }
    }

    private string GetStatFunStr()
    {
        string strFun = null;
        switch (Convert.ToInt16(this.DDL_StatisticType.SelectedValue))
        {
            case (int)EnumHelper.E_Stat_Fun.STAT_FUN_AVG:
                strFun = "avg";
                break;
            case (int)EnumHelper.E_Stat_Fun.STAT_FUN_COUNT:
                strFun = "count";
                break;
            default:
                strFun = "sum";
                break;
        }
        return strFun;
    }

    private void SetYTitle()
    {       
        switch (Convert.ToInt16(this.DDL_StatisticType.SelectedValue))
        {
            case (int)EnumHelper.E_Stat_Fun.STAT_FUN_AVG:
                MsChart.ChartAreas["ChartArea1"].AxisY.Title += " 平均值";
                break;
            case (int)EnumHelper.E_Stat_Fun.STAT_FUN_COUNT:
                MsChart.ChartAreas["ChartArea1"].AxisY.Title += " 总数目";
                break;
            default:
                MsChart.ChartAreas["ChartArea1"].AxisY.Title += " 总量";
                break;
        }        
    }

    private string GetStatComSql(ListItem item)
    {
        string strFun = GetStatFunStr();
        string selSql = "select " + strFun + "(" + item.Value + ") as " + item.Value + ", "
                   + xcolumn.SelectedValue + " from " + Session["tabcode"].ToString() + " group by " + xcolumn.SelectedValue;
        return selSql;     
    }

    private string GetStatDateSql(ListItem item)
    {
        string strDateType = null;
        switch (Convert.ToInt16(DDL_TimeSelect.SelectedValue))
        {
            case (int)EnumHelper.E_Stat_DateType.STAT_DATETYPE_DAY:
                strDateType = "'yyyy-mm-dd'"; //日
                break;
            case (int)EnumHelper.E_Stat_DateType.STAT_DATETYPE_WEEK: 
                strDateType = "'yyyy-IW'"; //周
                break;
            case (int)EnumHelper.E_Stat_DateType.STAT_DATETYPE_MONTH:
                strDateType = "'yyyy-mm'"; //月
                break;
            case (int)EnumHelper.E_Stat_DateType.STAT_DATETYPE_SEASON:
                strDateType = "'yyyy-Q'"; //季
                break;            
            default:            
                strDateType = "'yyyy'"; //年
                break;
        }

        string strFun = GetStatFunStr();

        //string selSql = "select to_char(" + xcolumn.SelectedValue + "," + strDateType + ")," + strFun + "(" + item.Value + ") from "
        //       + Session["tabcode"].ToString() + " group by to_char(" + xcolumn.SelectedValue + ","+strDateType+") order by to_char("
        //       + xcolumn.SelectedValue + "," + strDateType + ")";

        //此处用" as " + xcolumn.SelectedValue + "1，就是加了一个1，因为后面在图表显示的时候要对应，
        //即MsChart.Series[name].Points.DataBindXY(dv, xcolumn.SelectedValue + "1", dv, item.Value);dv里面就是as后面的内容
        //必须要有as，但是直接用" as " + xcolumn.SelectedValue，又不行，因为此sql语句有group by 和 order by，所以就加1
        //方便点
        DateTime stDate = Convert.ToDateTime(txtStartTime.Text.ToString());//获取开始时间
        DateTime enDate = Convert.ToDateTime(txtEndTime.Text.ToString());//获取结束时间
        string selSql = "select to_char(" + xcolumn.SelectedValue + "," + strDateType + ")" + " as " + xcolumn.SelectedValue + "1,"
           + strFun + "(" + item.Value + ")" + " as " + item.Value + " from " + Session["tabcode"].ToString()
           + " where " + xcolumn.SelectedValue + " > to_date('" + stDate + "','YYYY-MM-DD HH24:MI:SS')" + " and "
           + xcolumn.SelectedValue + " < to_date('" + enDate + "','YYYY-MM-DD HH24:MI:SS')"
           + " group by to_char(" + xcolumn.SelectedValue + "," + strDateType + ") order by to_char("
              + xcolumn.SelectedValue + "," + strDateType + ")";
        return selSql;
    }

    private DataSet GetQueryData(string selSql)
    {
        DataSet ds = null;
        if (string.IsNullOrEmpty(selSql))
        {
            ToAlert("设置有问题！");
            return ds;
        }
        
        try
        {
            ds = db.Query(selSql);
        }
        catch (Exception ex)
        {
            ToAlert("所选字段有问题（可能是数据类型不对）！" + ex.Message);
            return ds;
        }
        return ds;
    }

    private void SetChartScope(int num)
    {
        if (num > 50 && num < 150)
        {
            MsChart.Width = 1500;
            MsChart.Height = 1000;
        }
        else if (num > 200)
        {
            Response.Write("<script>alert('要显示的条目太大，共有：" + ds.Tables[0].Rows.Count + "项，超过200项图表显示不了，请重新选择！')</script>");
        
        }
    }

    protected void BtnCom_Click(object sender, EventArgs e)
    {
        InitChartSetting();

        int count = 0;
        foreach (ListItem item in ycolumn.Items)
        {
            if (item.Selected == true)
            {
                string selSql = GetStatComSql(item);

                DataSet ds = GetQueryData(selSql);
                if (ds == null)
                    break;
                SetChartScope(ds.Tables[0].Rows.Count);
                
                count++;
                if (count >= 2 && charttype.SelectedValue.ToString() == "3")
                {
                    Response.Write("<script>alert('不能为饼状图')</script>"); break;
                }
                ShowStat(ds, item, count, false);
            }
        }

        SetYTitle();
    }
   
    //有时间作为横坐标的统计
    protected void BtnDate_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtStartTime.Text.ToString()) || string.IsNullOrEmpty(txtEndTime.Text.ToString()))
        {
            Response.Write("<script>alert('请输入开始和结束时间!');</script>");
            return;
        }

        InitChartSetting();
       
        int count = 0;
        foreach (ListItem item in ycolumn.Items)
        {
            if (item.Selected == true)
            {
                string selSql = GetStatDateSql(item);
                DataSet ds = GetQueryData(selSql);
                if (ds == null)
                    break;
                SetChartScope(ds.Tables[0].Rows.Count);
                count++;
                if (count >= 2 && charttype.SelectedValue.ToString() == EnumHelper.E_Stat_ChartType.STAT_CHARTTYPE_PIE.ToString())
                {
                    Response.Write("<script>alert('不能为饼状图')</script>"); 
                    break;
                }
                ShowStat(ds, item, count, true);            
            }
        }
        SetYTitle();
    }

    protected void BtnBack_Click(object sender, EventArgs e)
    {
        string url = "CommonPage.aspx?IsReturn=true&table=" + Session["tabcode"].ToString();
        this.Page.Response.Redirect(url);
    }

    protected void BtnZoomOut_Click(object sender, EventArgs e)
    {
        MsChart.Width = 1500;
        MsChart.Height = 1000;
        BtnDate_Click(sender, e);
    }

    protected void BtnZoomIn_Click(object sender, EventArgs e)
    {
        MsChart.Width = 1500;
        MsChart.Height = 1000;
        BtnDate_Click(sender, e);
    }

    protected void chkAutoSize_Changed(object sender, EventArgs e)
    {
        if (chkAutoSize.Checked == true)
        {
            chkAutoSize.Checked = false;
            SetZoomSizeCtrl();
        }
        else
        {
            chkAutoSize.Checked = true;
            SetAutoSizeCtrl(); 
        }
    
    }

    private void SetAutoSizeCtrl()
    {
        lblHeight.Visible = false;
        lblWidth.Visible = false;
        txtHeight.Visible = false;
        txtWidth.Visible = false;
        ZoomIn.Visible = false;
        ZoomOut.Visible = false;
    }

    private void SetZoomSizeCtrl()
    {
        lblHeight.Visible = true;
        lblWidth.Visible = true;
        txtHeight.Visible = true;
        txtWidth.Visible = true;
        ZoomIn.Visible = true;
        ZoomOut.Visible = true;
    }
}


//    int gap=Convert.ToInt32(timeselect.SelectedValue);
//    DateTime stDate = Convert.ToDateTime(txtStartTime.Text.ToString());//获取开始时间
//    DateTime enDate = Convert.ToDateTime(txtEndTime.Text.ToString());//获取结束时间
//    string xx=xcolumn.SelectedValue.ToString();
//    string yy=item.Value.ToString();
//    TimeSpan ts = enDate - stDate;//开始与结束的间隔
//    int[] zu = new int[100];//记录每段的数值之和
//    DateTime[] zu1 = new DateTime[100];//记录每段的时间
//    int a=Convert.ToInt32(ts.TotalDays);
//    if (a / (gap * 30) < 1)//如果所选时间之差不足所选的一段时间，就计算全部
//    {
//        zu[0] = 0;
//        foreach (DataRow r in ds.Tables[0].Rows)
//        {
//            zu1[0] = st;
//            if (!string.IsNullOrEmpty(r[xx].ToString())) //没有时间（为空）的不参加计算
//            {
//                if (DateTime.Compare(Convert.ToDateTime(r[xx]), st) >= 0 && DateTime.Compare(en, Convert.ToDateTime(r[xx])) >= 0)
//                {
//                    // Response.Write(r[yy]);
//                    //zu1[i] = st.AddMonths(i*gap);
//                    zu[0] = Convert.ToInt32(r[yy]) + zu[0];
//                }
//            }
//        }

//        MsChart.Series[name].Points.AddXY(zu1[0].ToString("y"), zu[0]);
//        //Response.Write("<script>alert('时间选择不足')</script>"); break;
//    }

//    for (int i = 0; i <(a/(gap*30)); i++)
//    {
//       // Response.Write("i 的值："+i+"\n");
//        zu[i] = 0;
//        foreach(DataRow r in ds.Tables[0].Rows)
//        {
//            zu1[i] = st.AddMonths(i * gap);
//            if (!string.IsNullOrEmpty(r[xx].ToString())) //没有时间（为空）的不参加计算
//            {
//                if (DateTime.Compare(Convert.ToDateTime(r[xx]), st.AddMonths(i * gap)) >= 0 && DateTime.Compare(en, Convert.ToDateTime(r[xx])) >= 0 && DateTime.Compare(st.AddMonths((i + 1) * gap), Convert.ToDateTime(r[xx])) >= 0)//判断表中的时间属于哪一段，并且判断在这时间范围内
//                {
//                    // Response.Write(r[yy]);
//                    //zu1[i] = st.AddMonths(i*gap);
//                    zu[i] = Convert.ToInt32(r[yy]) + zu[i];
//                }
//            }
//        }
//        // Response.Write("shijian:"+zu1[i]+"liang:"+zu[i]);
//    }
//    for (int j = 0; j <(a / (gap*30)); j++)
//    {
//        MsChart.Series[name].Points.AddXY(zu1[j].ToString("y"), zu[j]);//将计算的各个点在图上显示
//    }
//        //MsChart.Series[name].XValueMember = xcolumn.SelectedValue.ToString();
//        //MsChart.Series[name].YValueMembers = item.Value.ToString();